import sys
import os

from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QListWidget, QMessageBox, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QDesktopServices
from PIL import Image
import fitz
import base64
import io
import shutil

class PDFConverter(QMainWindow):
    def __init__(self):
        super().__init__()

        app_path = os.path.dirname(os.path.abspath(__file__))
        self.OUTPUT_IMG = os.path.join(app_path, 'output_images')
        self.OUTPUT_FOLDER = os.path.join(app_path, 'output_folder')

        self.create_folders_if_not_exists()
        self.init_ui()

    def create_folders_if_not_exists(self):
        for folder in [self.OUTPUT_IMG, self.OUTPUT_FOLDER]:
            if not os.path.exists(folder):
                os.makedirs(folder)

    def init_ui(self):
        self.setWindowTitle('PDF 转 图片 & 图片 转 PDF')
        self.setGeometry(100, 100, 500, 400)
        self.setAcceptDrops(True)  # 确保窗口可以接受拖放
        self.setWindowIcon(QIcon('logo.ico'))

        self.label = QLabel("拖拽PDF文件到这里", self)
        self.label.resize(400, 20)
        self.label.move(50, 50)

        self.listbox = QListWidget(self)
        self.listbox.resize(400, 200)
        self.listbox.move(50, 100)
        self.listbox.itemClicked.connect(self.delete_selected)

        self.run_button = QPushButton('翻译', self)
        self.run_button.clicked.connect(self.convert_pdf_to_images_and_save_as_pdf)
        self.run_button.resize(100, 30)
        self.run_button.move(200, 350)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        file_paths = [u.toLocalFile() for u in event.mimeData().urls()]
        for file_path in file_paths:
            if file_path.lower().endswith('.pdf'):
                try:
                    # 直接将文件路径添加到列表中，不复制文件
                    self.listbox.addItem(file_path)
                    print(f"文件已添加: {file_path}")
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"无法添加文件: {e}")
            else:
                QMessageBox.warning(self, "警告", "这不是一个支持的PDF文件格式")

    def delete_selected(self):
        selected_index = self.listbox.currentRow()
        if selected_index >= 0:
            self.listbox.takeItem(selected_index)

    def convert_pdf_to_images_and_save_as_pdf(self):
        for i in range(self.listbox.count()):
            pdf_path = self.listbox.item(i).text()
            if '\\' in pdf_path:
                name=pdf_path.split('\\')[-1]
            else:
                name=pdf_path.split('/')[-1]
            import utils
            utils.convert_pdf_to_images(pdf_path,self.OUTPUT_IMG)
            utils.images_to_pdf(self.OUTPUT_IMG,os.path.join(self.OUTPUT_FOLDER, name))
            QMessageBox.information(self, "完成,确认打开所在文件夹", f"PDF转换完成，文件保存在：{os.path.join(self.OUTPUT_FOLDER, name)}")
            QDesktopServices.openUrl(QUrl.fromLocalFile(self.OUTPUT_FOLDER))
if __name__ == '__main__':
    app = QApplication(sys.argv)
    converter = PDFConverter()
    try:
        converter.show()
    except Exception as e:
        print(e)
    sys.exit(app.exec_())